#include "dns_parser.h"



static void dns_func_proc(int errcode, void *pdata, void* req, const char* ip) {
	
	retret(pdata)
	retret(req)
	CDnsParser* dns = static_cast<CDnsParser*>(pdata);
	dns_req_t* dnsreq = static_cast<dns_req_t*>(req);

	if (!errcode) {
		dns->dns_func(req, dnsreq->name, dnsreq->url, ip, dnsreq->cb);
	}
	else {
		dns->dns_errorfunc(req, dnsreq->name, dnsreq->url, ip, dnsreq->cb);
	}

}
static void dns_end_func_proc(int errcode, void *pdata, void* req, const char* ip) {

	retret(pdata)
	retret(req)
	CDnsParser* dns = (CDnsParser*)(pdata);
	dns_req_t* dnsreq = (dns_req_t*)(req);
	dns->dns_endfunc(req, dnsreq->name, dnsreq->url, ip, dnsreq->cb);
}
static void dns_thread_proc(int istart, void *pdata) {

	retret(pdata)
	CDnsParser* dns = (CDnsParser*)(pdata);

	dns->dns_signal(istart);
}

CDnsParser::CDnsParser() {

	irun = 0;

}
CDnsParser::~CDnsParser() {

}
void CDnsParser::dnsinit() {

	dns_init(&dns, dns_thread_proc,this);

}
void CDnsParser::dnsuninit() {

	dns_free(&dns);
}
void CDnsParser::dnsaddnamsserver(const char* addr) {

	dns_addaddress(&dns, addr);
}
dns_req_t* CDnsParser::dnsreq(const char* url, const char* name, void* cb) {


	dns_req_t* req = (dns_req_t*)calloc(1,sizeof(dns_req_t));
	retrtpv(req, 0)

	req->cb = cb;

	req->data = this;
	req->func = dns_func_proc;
	req->end = dns_end_func_proc;
	int ilen;

	ilen = 0;
	ilen = strlen(url);
	req->url = (char*)calloc((ilen + 1),sizeof(char));
	strcpy(req->url, url);

	ilen = 0;
	ilen = strlen(name);
	req->name = (char*)calloc((ilen + 1), sizeof(char));
	strcpy(req->name, name);

	if (dns_req(&dns, req)){
		return req;
	}
	dnsreqfree(req);

	return NULL;

}
void CDnsParser::dnsreqfree(void* req) {

	retret(req)
	dns_req_t* dnsreq = (dns_req_t*)(req);

	//dns_canecl_req(dnsreq);

	if (dnsreq->name) {
		free(dnsreq->name);
		dnsreq->name = NULL;
	}
	if(dnsreq->url) {
		free(dnsreq->url);
		dnsreq->url = NULL;
	}
	if (dnsreq) {
		free(dnsreq);
		dnsreq = NULL;
	}
}
void CDnsParser::dnswait() {
	runloop(&dns);
}
